import axios from 'axios'
import {
  ElMessage
} from 'element-plus'
import {
  isInclude
} from "@/utils"
import store from "@/store"

/**
 * 防重复点击发送请求
 */
let pending = [];
let cancelToken = axios.CancelToken;
let removePending = (ever) => {
  for (let p in pending) {
    if (`${ever.url}&${ever.method}`.endsWith(pending[p].u) && JSON.stringify(pending[p].d) === ever.data) {
      ever.cancelToken = new cancelToken(c => c());
      pending.splice(p, 1);
    }
  }
}
const service = axios.create({
  // url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API,
  // request timeout
  timeout: 50000 // request timeout
})

// requets拦截
service.interceptors.request.use(
  config => {
    //在一个发送前执行一下取消操作
    removePending(config);
    if (typeof config.headers['Content-Type'] == 'undefined') {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    }
    config.cancelToken = new cancelToken((c) => {
      pending.push({
        u: `${config.url}&${config.method}`,
        d: config.data,
        f: c
      });
    });
    if (!isInclude(config, "LOAD_ING") || config.LOAD_ING) {
      store.commit("settings/SET_LOADING", true)
    }
    if (isInclude(config, "LOAD_ING") && !config.LOAD_ING) {
      store.commit("settings/SET_LOADING", false)
    }
    return config
  },
  error => {
    store.state.settings.$loading && store.commit("settings/SET_LOADING", false);
    return Promise.reject(error)
  }
)

//response 拦截
service.interceptors.response.use(response => {
    removePending(response.config);
    if (response.data.code != 200) {
      ElMessage.error(response.data.msg)
    }
    store.state.settings.$loading && store.commit("settings/SET_LOADING", false);
    return response.data
  },
  error => {
    const {
      response
    } = error;
    store.state.settings.$loading && store.commit("settings/SET_LOADING", false);
    ElMessage.error(`timestamp:${new Date().getTime()}接口：${response.config.url}(status:${response.status})`)
    return Promise.reject(response)
  }
)
export default service